# -*- coding: utf-8 -*-
"""
yanzg
"""
import logging
import json
import time

from django.contrib.auth import logout
from django.http import JsonResponse
from django.contrib import auth
from django.views.decorators.http import require_POST,require_GET
from django.views.decorators.csrf import csrf_exempt
from django.middleware import csrf
from blueapps.utils.sops_jwt_handler import SopsJwtHandler
from blueapps.account.decorators import login_exempt
from blueapps.account.forms import LoginForm
from blueapps.account.handlers.response import ResponseHandler
from blueapps.account import ConfFixture
from gcloud.conf import settings

logger = logging.getLogger("root")



def get_csrf_token(request):
    """
    前端获取csrf_token接口
    """
    csrf_token = csrf.get_token(request)
    return JsonResponse({"csrf_token": csrf_token})

@csrf_exempt
@login_exempt
@require_POST
def login(request):

    data = json.loads(request.body)
    # yanzg 使用form对象校验输入格式
    form = LoginForm(data)

    if not form.is_valid():
        logger.debug(
            u"[login]登录输入校验异常，url：{}，params：{}, errors: {}".format(
                request.path_info, request.POST, form.errors
            )
        )
        # error ret
        return JsonResponse({
            "code": 46100,
            "data": "null",
            "message": "用户密码输入有误",
        })

    username = form.cleaned_data["username"]
    password = form.cleaned_data["password"]

    # 使用auth backend 查询用户密码, 过auth_backend: sopsSession
    user = auth.authenticate(request, username=username,password=password)
    # user存在通过并获取db里的User记录, 同时request不存在user（django固定做法通常为判定是否login）
    if user and user.username != request.user.username:
        # 给django auth执行login动作,框架会进行一些动作,如 request填充User数据、is_auth、session等
        auth.login(request, user)
        # 如果是ajax,签发token
        token = ""
        if request.is_ajax:
            token = SopsJwtHandler(request).generate_jwt_token()
            logger.debug(token)
            pass
        # 登录成功的返回
        return JsonResponse(
            {
                "result": True,
                "code": 0,
                "data": {
                    "id": request.user.id,
                    "username": request.user.username,
                    "token": token ,
                    "timestamp": time.time()
                },
                "message": "ok",
            }
        )


    return JsonResponse({
        "result": False,
        "code": 401,
        "data": "null",
        "message": "用户密码认证失败",
    })


@require_GET
def user_logout(request):
    """
    yanzg copy form gcloud.core.views
    :param request:
    :return:
    """
    logout(request)
    # 验证不通过，需要跳转至统一登录平台
    # request.path = request.path.replace("logout", "")
    # handler = ResponseHandler(ConfFixture, settings)
    # return handler.build_401_response(request)
    return JsonResponse({
        "result": False,
        "code": 401,
        "data": "null,replace this data, cur_path can send fronted",
        "message": "已退出,或登录会话失效",
    },status=401)

